<template>
  <div class="assessment-fill-container">
    <el-card class="search-card">
      <el-form :model="searchForm" label-width="80px">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="考核方案">
              <el-select v-model="searchForm.assessmentId" placeholder="请选择考核方案" clearable>
                <el-option
                  v-for="assessment in assessmentList"
                  :key="assessment.id"
                  :label="assessment.name"
                  :value="assessment.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="员工姓名">
              <el-input v-model="searchForm.employeeName" placeholder="请输入员工姓名" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="部门">
              <el-tree-select
                v-model="searchForm.departmentId"
                :data="departmentOptions"
                :props="{
                  value: 'id',
                  label: 'name',
                  children: 'children'
                }"
                placeholder="请选择所属部门"
                style="width: 200px"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="填写状态">
              <el-select v-model="searchForm.fillStatus" placeholder="请选择状态" clearable>
                <el-option label="未开始" value="not_started" />
                <el-option label="进行中" value="in_progress" />
                <el-option label="已完成" value="completed" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24" style="text-align: right;">
            <el-button type="primary" @click="handleSearch">查询</el-button>
            <el-button @click="resetSearch">重置</el-button>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <el-card class="table-card">
      <template #header>
        <div class="card-header">
          <span>考核填写列表</span>
          <!-- <div>
            <el-button type="primary" @click="exportData">导出数据</el-button>
            <el-button @click="refreshData">刷新</el-button>
          </div> -->
        </div>
      </template>

      <el-table
        :data="tableData"
        v-loading="loading"
        style="width: 100%"
        :default-sort="{ prop: 'createTime', order: 'descending' }"
      >
        <el-table-column prop="assessmentName" label="考核方案" min-width="150" />
        <el-table-column prop="employeeName" label="员工姓名" min-width="100" />
        <el-table-column prop="employeeId" label="员工工号" min-width="100" />
        <el-table-column prop="departmentId" label="部门" min-width="120" />
        <el-table-column prop="finalScore" label="最终分数" min-width="100" />
        <el-table-column prop="fillStatus" label="填写状态" min-width="100">
          <template #default="{ row }">
            <el-tag
              :type="getStatusTagType(row.fillStatus)"
              size="small"
            >
              {{ getStatusText(row.fillStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="submitTime" label="提交时间" min-width="120" />
        <el-table-column prop="createTime" label="创建时间" min-width="120" />
        <el-table-column label="操作" fixed="right" width="200">
          <template #default="{ row }">
            <el-button
              type="primary"
              size="small"
              @click="viewDetails(row)"
              :disabled="row.fillStatus === 'not_started'"
            >
              查看详情
            </el-button>
            <el-button
              v-if="row.fillStatus === 'completed'"
              type="success"
              size="small"
              @click="handleAIAnalysis(row)"
            >
              绩效AI分析
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 考核填写详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      :title="`考核填写详情 - ${currentFill?.employeeName}`"
      width="80%"
      :close-on-click-modal="false"
    >
      <div v-if="currentFill" class="fill-detail">
        <el-descriptions :column="3" border>
          <el-descriptions-item label="考核方案">{{ currentFill.assessmentName }}</el-descriptions-item>
          <el-descriptions-item label="员工姓名">{{ currentFill.employeeName }}</el-descriptions-item>
          <el-descriptions-item label="员工工号">{{ currentFill.employeeId }}</el-descriptions-item>
          <el-descriptions-item label="部门">{{ getDepartmentName(currentFill.departmentId) }}</el-descriptions-item>
          <el-descriptions-item label="填写状态">
            <el-tag :type="getStatusTagType(currentFill.fillStatus)">
              {{ getStatusText(currentFill.fillStatus) }}
            </el-tag>
          </el-descriptions-item>
        </el-descriptions>

        <el-divider />

        <h4>KPI填写详情</h4>
        <el-table :data="kpiDetails" style="width: 100%; margin-top: 20px;">
          <el-table-column prop="kpiName" label="KPI名称" min-width="150" />
          <el-table-column prop="kpiWeight" label="权重" min-width="60" />
          <el-table-column prop="selfScore" label="自评分数" min-width="80" />
          <el-table-column prop="selfComment" label="自评说明" min-width="120" show-overflow-tooltip />
          <el-table-column label="HR评分" width="150" align="left">
          <template #default="{ row }">
            <div v-if="row.editing">
              <el-input-number
                v-model="row.editingManagerScore"
                :min="0"
                :max="100"
                :precision="1"
                size="small"
                @blur="saveManagerScore(row)"
                @keyup.enter="saveManagerScore(row)"
              />
            </div>
            <div v-else @click="startEditing(row, 'managerScore')" style="cursor: pointer;">
              {{ row.managerScore || '-' }}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="HR评语" width="180" show-overflow-tooltip>
          <template #default="{ row }">
            <div v-if="row.editingComment">
              <el-input
                v-model="row.editingManagerComment"
                type="textarea"
                :rows="2"
                size="small"
                @blur="saveManagerComment(row)"
                @keyup.enter="saveManagerComment(row)"
              />
            </div>
            <div v-else @click="startEditing(row, 'managerComment')" style="cursor: pointer;">
              {{ row.managerComment || '-' }}
            </div>
          </template>
        </el-table-column>
          <el-table-column prop="status" label="状态" min-width="100">
            <template #default="{ row }">
              <el-tag size="small">
                {{ getKPIStatusText(row.status) }}
              </el-tag>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-dialog>

    <!-- 审批对话框 -->
    <el-dialog
      v-model="approveDialogVisible"
      :title="`${approveAction === 'approve' ? '审批通过' : '驳回'}考核填写`"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form :model="approveForm" label-width="80px">
        <el-form-item label="审批意见" prop="comment">
          <el-input
            v-model="approveForm.comment"
            type="textarea"
            :rows="4"
            placeholder="请输入审批意见"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="approveDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmApprove">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- AI分析对话框 -->
    <el-dialog
      v-model="aiAnalysisDialogVisible"
      title="绩效AI分析"
      width="600px"
      :close-on-click-modal="false"
    >
      <div v-if="currentAIAnalysisFill">
        <el-form label-width="100px">
          <el-form-item label="员工姓名">
            <el-input :value="currentAIAnalysisFill.employeeName" disabled />
          </el-form-item>
          <el-form-item label="所属部门">
            <el-input :value="getDepartmentName(currentAIAnalysisFill.departmentId)" disabled />
          </el-form-item>
          <el-form-item label="考核方案">
            <el-input :value="currentAIAnalysisFill.assessmentName" disabled />
          </el-form-item>
          <el-form-item label="AI分析结果">
            <el-input
              v-model="currentAIAnalysisFill.aiResult"
              type="textarea"
              :rows="8"
              placeholder="AI分析结果将在这里显示"
              :disabled="!currentAIAnalysisFill.aiResult"
            />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="aiAnalysisDialogVisible = false">关闭</el-button>
          <el-button 
            type="primary" 
            :loading="aiAnalyzing"
            @click="performAIAnalysis"
          >
            生成AI分析
          </el-button>
          <el-button 
            type="success" 
            @click="aiAnalysisDialogVisible = false"
            :disabled="aiAnalyzing"
          >
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { AssessmentFillData, KPIFillDetailData } from '@/api/assessment-fill'
import { getAssessmentFillPage, getAssessmentFillDetail, approveAssessmentFill, submitKPIManagerScore, submitKPIFinalScore, aiAnalysis } from '@/api/assessment-fill'
import { getAssessmentList } from '@/api/assessments'
import type { AssessmentData } from '@/api/assessments'
import { DepartmentData, getDepartmentList } from '@/api/departments'

// 搜索表单
const searchForm = reactive({
  assessmentId: undefined as number | undefined,
  employeeName: '',
  departmentId: '',
  fillStatus: ''
})

// 分页信息
const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 表格数据
const tableData = ref<AssessmentFillData[]>([])
const loading = ref(false)

// 考核方案列表
const assessmentList = ref<AssessmentData[]>([])

// 详情对话框
const detailDialogVisible = ref(false)
const currentFill = ref<AssessmentFillData | null>(null)
const kpiDetails = ref<KPIFillDetailData[]>([])

// 部门选项
const departmentOptions = ref<Department[]>([])

// 将平铺的部门数据转换为树形结构
function buildDepartmentTree(departments: any[]): any[] {
  const departmentMap = new Map()
  const tree: any[] = []
  
  // 首先将所有部门存入map
  departments.forEach(dept => {
    departmentMap.set(dept.id, { ...dept, children: [] })
  })
  
  // 构建树形结构
  departments.forEach(dept => {
    const node = departmentMap.get(dept.id)
    if (dept.parentId) {
      const parent = departmentMap.get(dept.parentId)
      if (parent) {
        parent.children.push(node)
      }
    } else {
      tree.push(node)
    }
  })
  
  return tree
}

// 审批对话框
const approveDialogVisible = ref(false)
const approveForm = reactive({
  comment: ''
})
const currentApproveFill = ref<AssessmentFillData | null>(null)
const approveAction = ref<'approve' | 'reject'>('approve')

// AI分析对话框
const aiAnalysisDialogVisible = ref(false)
const currentAIAnalysisFill = ref<AssessmentFillData | null>(null)
const aiAnalyzing = ref(false)

// 部门列表
const departmentList = ref<DepartmentData[]>([])

// 状态标签类型映射
const getStatusTagType = (status: string) => {
  const map: Record<string, string> = {
    not_started: 'info',
    in_progress: 'warning',
    completed: 'success',
    submitted: 'primary',
    approved: 'success',
    rejected: 'danger'
  }
  return map[status] || 'info'
}

// 状态文本映射
const getStatusText = (status: string) => {
  const map: Record<string, string> = {
    not_started: '未开始',
    in_progress: '进行中',
    completed: '已完成'
  }
  return map[status] || '未知'
}

const getDepartmentName = (departmentId: number) => {
  const department = departmentList.value.find(dep => dep.id === departmentId)
  return department?.name || '未知部门'
}

// KPI状态文本映射
const getKPIStatusText = (status: string) => {
  const map: Record<string, string> = {
    not_started: '未开始',
    self_filled: '已自评',
    manager_reviewed: 'HR已评',
    completed: '已完成'
  }
  return map[status] || '未知'
}

// 进度条状态
const getProgressStatus = (progress: number) => {
  if (progress >= 100) return 'success'
  if (progress >= 50) return ''
  return 'exception'
}

// 加载考核方案列表
const loadAssessmentList = async () => {
  try {
    const response = await getAssessmentList({})
    assessmentList.value = response
  } catch (error) {
    console.error('加载考核方案列表失败:', error)
  }
}

// 加载表格数据
const loadTableData = async () => {
  loading.value = true
  try {
    const params = {
      current: pagination.current,
      size: pagination.size,
      ...searchForm
    }
    
    const response = await getAssessmentFillPage(params)
    tableData.value = response.records
    pagination.total = response.total
  } catch (error) {
    console.error('加载考核填写数据失败:', error)
    ElMessage.error('加载数据失败')
  } finally {
    loading.value = false
  }
}

// 查看详情
const viewDetails = async (row: AssessmentFillData) => {
  try {
    const response = await getAssessmentFillDetail(row.id)
    currentFill.value = response.assessmentFills
    kpiDetails.value = response.kpiFillDetailsList
    detailDialogVisible.value = true
  } catch (error) {
    console.error('获取考核填写详情失败:', error)
    ElMessage.error('获取详情失败')
  }
}

// 处理审批
const handleApprove = (row: AssessmentFillData, approved: boolean) => {
  currentApproveFill.value = row
  approveAction.value = approved ? 'approve' : 'reject'
  approveForm.comment = ''
  approveDialogVisible.value = true
}

// 处理绩效AI分析
const handleAIAnalysis = (row: AssessmentFillData) => {
  currentAIAnalysisFill.value = row
  aiAnalysisDialogVisible.value = true
}

// 执行AI分析
const performAIAnalysis = async () => {
  if (!currentAIAnalysisFill.value) return
  
  aiAnalyzing.value = true
  try {
    const response = await aiAnalysis(currentAIAnalysisFill.value.id)
    if (response) {
      ElMessage.success('AI分析生成成功')
      // 重新加载数据以获取最新的aiResult
      await loadTableData()
      // 更新当前对话框中的aiResult
      const updatedFill = tableData.value.find(item => item.id === currentAIAnalysisFill.value?.id)
      if (updatedFill && currentAIAnalysisFill.value) {
        currentAIAnalysisFill.value.aiResult = updatedFill.aiResult
      }
    }
  } catch (error) {
    console.error('AI分析失败:', error)
    ElMessage.error('AI分析失败')
  } finally {
    aiAnalyzing.value = false
  }
}

// 开始编辑
const startEditing = (row: any, field: string) => {
  // 重置所有编辑状态
  kpiDetails.value.forEach(item => {
    item.editing = false
    item.editingComment = false
    item.editingFinal = false
  })
  
  // 设置当前编辑字段
  if (field === 'managerScore') {
    row.editing = true
    row.editingManagerScore = row.managerScore
  } else if (field === 'managerComment') {
    row.editingComment = true
    row.editingManagerComment = row.managerComment
  } else if (field === 'finalScore') {
    row.editingFinal = true
    row.editingFinalScore = row.finalScore
  }
  
  // 聚焦到输入框
  nextTick(() => {
    const input = document.querySelector('.el-input-number__inner, .el-textarea__inner') as HTMLElement
    input?.focus()
  })
}

// 保存HR评分
const saveManagerScore = async (row: any) => {
  try {
    if (row.editingManagerScore !== row.managerScore) {
      const response = await submitKPIManagerScore(
        row.id,
        row.editingManagerScore,
        row.managerComment || ''
      )
      
      if (response) {
        row.managerScore = row.editingManagerScore
        ElMessage.success('HR评分保存成功')
      }
    }
    row.editing = false
  } catch (error) {
    console.error('保存HR评分失败:', error)
    ElMessage.error('保存HR评分失败')
    row.editing = false
  }
}

// 保存HR评语
const saveManagerComment = async (row: any) => {
  try {
    if (row.editingManagerComment !== row.managerComment) {
      const response = await submitKPIManagerScore(
        row.id,
        row.managerScore || 0,
        row.editingManagerComment
      )
      
      if (response) {
        row.managerComment = row.editingManagerComment
        ElMessage.success('HR评语保存成功')
      }
    }
    row.editingComment = false
  } catch (error) {
    console.error('保存HR评语失败:', error)
    ElMessage.error('保存HR评语失败')
    row.editingComment = false
  }
}

// 保存最终分数
const saveFinalScore = async (row: any) => {
  try {
    if (row.editingFinalScore !== row.finalScore) {
      // 这里需要调用更新最终分数的API
      const response = await submitKPIFinalScore(
        row.id,
        row.editingFinalScore
      )
      
      if (response) {
        row.finalScore = row.editingFinalScore
        ElMessage.success('最终分数保存成功')
      }
    }
    row.editingFinal = false
  } catch (error) {
    console.error('保存最终分数失败:', error)
    ElMessage.error('保存最终分数失败')
    row.editingFinal = false
  }
}

// 确认审批
const confirmApprove = async () => {
  if (!currentApproveFill.value) return
  
  try {
    const response = await approveAssessmentFill(
      currentApproveFill.value.id,
      approveAction.value === 'approve',
      approveForm.comment
    )
    
    if (response.data) {
      ElMessage.success(approveAction.value === 'approve' ? '审批通过成功' : '驳回成功')
      approveDialogVisible.value = false
      loadTableData()
    }
  } catch (error) {
    console.error('审批操作失败:', error)
    ElMessage.error('审批操作失败')
  }
}

// 搜索
const handleSearch = () => {
  pagination.current = 1
  loadTableData()
}

// 重置搜索
const resetSearch = () => {
  Object.assign(searchForm, {
    assessmentId: undefined,
    employeeName: '',
    departmentId: '',
    fillStatus: ''
  })
  pagination.current = 1
  loadTableData()
}

// 刷新数据
const refreshData = () => {
  loadTableData()
}

// 导出数据
const exportData = () => {
  ElMessage.info('导出功能待实现')
}

// 分页大小变化
const handleSizeChange = (size: number) => {
  pagination.size = size
  pagination.current = 1
  loadTableData()
}

// 当前页变化
const handleCurrentChange = (current: number) => {
  pagination.current = current
  loadTableData()
}

const loadDepartmentList = async () => {
  try {
    const response = await getDepartmentList()
    departmentList.value = response
    departmentOptions.value = buildDepartmentTree(response)
  } catch (error) {
    console.error('加载部门列表失败:', error)
  }
}

// 初始化
onMounted(() => {
  loadAssessmentList()
  loadTableData()
  loadDepartmentList()
})
</script>

<style scoped>
.assessment-fill-container {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.table-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.fill-detail {
  max-height: 60vh;
  overflow-y: auto;
}

.fill-detail h4 {
  margin: 0 0 16px 0;
  color: #303133;
}
</style>